<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
  const allRelationshipsByEntityNeedingOptions = Object
    .values(relationshipsByOtherEntity)
    .map(relationships => relationships.filter(rel => rel.persistableRelationship && !rel.otherEntity.embedded))
    .filter(relationships => relationships.length > 0);
_%>
import { Component, inject, signal, OnInit<% if (anyFieldHasImageContentType) { %>, ElementRef<% } %> } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { finalize<% if (relationships.some(rel => rel.persistableRelationship)) { %>, map<% } %> } from 'rxjs/operators';

import SharedModule from 'app/shared/shared.module';
import { ReactiveFormsModule } from '@angular/forms';

import { <%= entityAngularName %>FormService, <%= entityAngularName %>FormGroup } from './<%= entityFileName %>-form.service';
import { I<%= entityAngularName %> } from '../<%= entityFileName %>.model';
import { <%= entityAngularName %>Service } from '../service/<%= entityFileName %>.service';
<%_ if (anyFieldIsBlobDerived) { _%>
import { AlertErrorModel } from 'app/shared/alert/alert-error.model';
import { EventManager, EventWithContent } from 'app/core/util/event-manager.service';
import { DataUtils, FileLoadError } from 'app/core/util/data-util.service';
<%_ } _%>
<%_ for (const relationshipsByEntityNeedingOptions of allRelationshipsByEntityNeedingOptions) {
    const uniqueRel = relationshipsByEntityNeedingOptions[0];
    if (uniqueRel.otherEntity.entityAngularName !== entityAngularName) {
_%>
import { I<%= uniqueRel.otherEntity.entityAngularName %> } from 'app/entities/<%= uniqueRel.otherEntity.entityFolderName %>/<%= uniqueRel.otherEntity.entityFileName %>.model';
import { <%= uniqueRel.otherEntity.entityAngularName %>Service } from 'app/entities/<%= uniqueRel.otherEntity.entityFolderName %>/service/<%= uniqueRel.otherEntity.entityFileName %>.service';
<%_
    }
  }
_%>
<%_ const enumImports = generateEntityClientEnumImports(fields); _%>
<%_ enumImports.forEach( (importedPath, importedType) => { _%>
import { <%- importedType %> } from '<%- importedPath %>';
<%_ }); _%>

@Component({
    selector: '<%= jhiPrefixDashed %>-<%= entityFileName %>-update',
    templateUrl: './<%= entityFileName %>-update.html',
    imports: [SharedModule, ReactiveFormsModule],
})
export class <%= entityAngularName %>Update implements OnInit {
    isSaving = false;
    <%= entityInstance %>: I<%= entityAngularName %> | null = null;
<%_ enumImports.forEach( (importedPath, importedType) => { _%>
    <%- this._.lowerFirst(importedType) %>Values = Object.keys(<%- importedType %>);
<%_ }); _%>

<%_ for (const relationshipsByEntityNeedingOptions of allRelationshipsByEntityNeedingOptions) { _%>
  <%_ const relationshipsWithCustomUniqueOptions = relationshipsByEntityNeedingOptions.filter(rel => rel.relationshipOneToOne && rel.otherRelationship); _%>
  <%_ if (relationshipsByEntityNeedingOptions.length > relationshipsWithCustomUniqueOptions.length) { _%>
    <%_ const otherEntity = relationshipsByEntityNeedingOptions[0].otherEntity _%>
    <%= otherEntity.entityInstancePlural %>SharedCollection = signal<I<%= otherEntity.entityAngularName %>[]>([]);
  <%_ } _%>
  <%_ for (const relationship of relationshipsWithCustomUniqueOptions) { _%>
    <%= relationship.relationshipFieldNamePlural %>Collection = signal<I<%= relationship.otherEntity.entityAngularName %>[]>([]);
  <%_ } _%>
<%_ } _%>

<%_ if (anyFieldIsBlobDerived) { _%>
    protected dataUtils = inject(DataUtils);
    protected eventManager = inject(EventManager);
<%_ } _%>
    protected <%= entityInstance %>Service = inject(<%= entityAngularName %>Service);
    protected <%= entityInstance %>FormService = inject(<%= entityAngularName %>FormService);
<%_ for (const relationshipsByEntityNeedingOptions of allRelationshipsByEntityNeedingOptions) {
    const uniqueRel = relationshipsByEntityNeedingOptions[0];
    if (uniqueRel.otherEntity.entityAngularName !== entityAngularName) {
_%>
    protected <%= uniqueRel.otherEntity.entityInstance %>Service = inject(<%= uniqueRel.otherEntity.entityAngularName %>Service);
<%_
    }
  }
_%>
<%_ if (anyFieldHasImageContentType) { _%>
    protected elementRef = inject(ElementRef);
<%_ } _%>
    protected activatedRoute = inject(ActivatedRoute);

    // eslint-disable-next-line @typescript-eslint/member-ordering
    editForm: <%= entityAngularName %>FormGroup = this.<%= entityInstance %>FormService.create<%= entityAngularName %>FormGroup();

<%_ for (const relationshipsByEntityNeedingOptions of allRelationshipsByEntityNeedingOptions) {
      const { otherEntity } = relationshipsByEntityNeedingOptions[0];
_%>

    compare<%= otherEntity.entityAngularName %> = (o1: I<%= otherEntity.entityAngularName %> | null, o2: I<%= otherEntity.entityAngularName %> | null): boolean =>
        this.<%= otherEntity.entityInstance %>Service.compare<%= otherEntity.entityAngularName %>(o1, o2);
<%_ } _%>

    ngOnInit(): void {
        this.activatedRoute.data.subscribe(({ <%= entityInstance %> }) => {
            this.<%= entityInstance %> = <%= entityInstance %>;
            if (<%= entityInstance %>) {
                this.updateForm(<%= entityInstance %>);
            }

<%_ if (relationships.filter(rel => rel.persistableRelationship && !rel.otherEntity.embedded).length > 0) { _%>
            this.loadRelationshipsOptions();
<%_ } _%>
        });
    }

<%_ if (anyFieldIsBlobDerived) { _%>
    byteSize(base64String: string): string {
        return this.dataUtils.byteSize(base64String);
    }

    openFile(base64String: string, contentType: string | null | undefined): void {
        this.dataUtils.openFile(base64String, contentType);
    }

    setFileData(event: Event, field: string, isImage: boolean): void {
        this.dataUtils.loadFileToForm(event, this.editForm, field, isImage).subscribe({
            error: (err: FileLoadError) =>
                this.eventManager.broadcast(
                    new EventWithContent<AlertErrorModel>('<%= frontendAppName %>.error', { <% if (enableTranslation) { %>...err, key: 'error.file.' + err.key<% } else { %>message: err.message<% } %> })
                )
        });
    }

  <%_ if (anyFieldHasImageContentType) { _%>
    clearInputImage(field: string, fieldContentType: string, idInput: string): void {
        this.editForm.patchValue({
            [field]: null,
            [fieldContentType]: null
        });
        if (idInput && this.elementRef.nativeElement.querySelector('#' + idInput)) {
            this.elementRef.nativeElement.querySelector('#' + idInput).value = null;
        }
    }
  <%_ } _%>
<%_ } _%>

    previousState(): void {
        globalThis.history.back();
    }

    save(): void {
        this.isSaving = true;
        const <%= entityInstance %> = this.<%= entityInstance %>FormService.get<%= entityAngularName %>(this.editForm);
<%_ if (updatableEntity) { _%>
        if (<%= entityInstance %>.<%= primaryKey.name %> === null) {
<%_ } _%>
            this.subscribeToSaveResponse(this.<%= entityInstance %>Service.create(<%= entityInstance %>));
<%_ if (updatableEntity) { _%>
        } else {
            this.subscribeToSaveResponse(this.<%= entityInstance %>Service.update(<%= entityInstance %>));
        }
<%_ } _%>
    }

    protected subscribeToSaveResponse(result: Observable<HttpResponse<I<%= entityAngularName %>>>): void {
        result.pipe(finalize(() => this.onSaveFinalize())).subscribe({
            next: () => this.onSaveSuccess(),
            error: () => this.onSaveError()
        });
    }

    protected onSaveSuccess(): void {
        this.previousState();
    }

    protected onSaveError(): void {
        // Api for inheritance.
    }

    protected onSaveFinalize(): void {
        this.isSaving = false;
    }

    protected updateForm(<%= entityInstance %>: I<%= entityAngularName %>): void {
        this.<%= entityInstance %> = <%= entityInstance %>;
        this.<%= entityInstance %>FormService.resetForm(this.editForm, <%= entityInstance %>);
<%_ if (relationships.filter(rel => rel.persistableRelationship).length > 0) { _%>

  <%_ for (const relationshipsByEntityNeedingOptions of allRelationshipsByEntityNeedingOptions) { _%>
    <%_ const relationshipsWithCustomUniqueOptions = relationshipsByEntityNeedingOptions.filter(rel => rel.relationshipOneToOne && rel.otherRelationship); _%>
    <%_ const relationshipsWithCustomSharedOptions = relationshipsByEntityNeedingOptions.filter(rel => !relationshipsWithCustomUniqueOptions.includes(rel)); _%>
    <%_ if (relationshipsWithCustomSharedOptions.length > 0) { _%>
      <%_ const otherEntity = relationshipsByEntityNeedingOptions[0].otherEntity _%>
        this.<%= otherEntity.entityInstancePlural %>SharedCollection.set(this.<%= otherEntity.entityInstance %>Service.add<%= otherEntity.entityAngularName %>ToCollectionIfMissing<I<%= otherEntity.entityAngularName %>>(
            this.<%= otherEntity.entityInstancePlural %>SharedCollection(),
      <%_ for (const relationship of relationshipsWithCustomSharedOptions) { _%>
            <%= relationship.collection ? '...(' : '' %><%= entityInstance %>.<%= relationship.propertyName %><%= relationship.collection ? ' ?? [])' : '' %>,
      <%_ } _%>
        ));
    <%_ } _%>
    <%_ for (const relationship of relationshipsWithCustomUniqueOptions) { _%>
      <%_ const otherEntity = relationship.otherEntity _%>
        this.<%= relationship.relationshipFieldNamePlural %>Collection.set(
          this.<%= otherEntity.entityInstance %>Service.add<%= otherEntity.entityAngularName %>ToCollectionIfMissing<I<%= otherEntity.entityAngularName %>>(
            this.<%= relationship.relationshipFieldNamePlural %>Collection(),
            <%= relationship.collection ? '...(' : '' %><%= entityInstance %>.<%= relationship.propertyName %><%= relationship.collection ? ' ?? [])' : '' %>,
          ),
        );
    <%_ } _%>
  <%_ } _%>
<%_ } _%>
    }

<%_ if (relationships.filter(rel => rel.persistableRelationship && !rel.otherEntity.embedded).length > 0) { _%>
    protected loadRelationshipsOptions(): void {
  <%_ for (const relationshipsByEntityNeedingOptions of allRelationshipsByEntityNeedingOptions) { _%>
    <%_ const relationshipsWithCustomUniqueOptions = relationshipsByEntityNeedingOptions.filter(rel => rel.relationshipOneToOne && rel.otherRelationship); %>
    <%_ const relationshipsWithCustomSharedOptions = relationshipsByEntityNeedingOptions.filter(rel => !relationshipsWithCustomUniqueOptions.includes(rel)); %>
    <%_ const { otherEntity } = relationshipsByEntityNeedingOptions[0] _%>
    <%_ if (relationshipsWithCustomSharedOptions.length > 0) { _%>
        this.<%= otherEntity.entityInstance %>Service
            .query()
            .pipe(map((res: HttpResponse<I<%= otherEntity.entityAngularName %>[]>) => res.body ?? []))
            .pipe(map((<%= otherEntity.entityInstancePlural %>: I<%= otherEntity.entityAngularName %>[]) => this.<%= otherEntity.entityInstance %>Service.add<%= otherEntity.entityAngularName %>ToCollectionIfMissing<I<%= otherEntity.entityAngularName %>>(
                <%= otherEntity.entityInstancePlural %>,
      <%_ for (const relationship of relationshipsWithCustomSharedOptions) { _%>
        <%_ if (relationship.collection) { _%>
                ...(this.<%= entityInstance %>?.<%= relationship.propertyName %> ?? []),
        <%_ } else { _%>
                this.<%= entityInstance %>?.<%= relationship.propertyName %>,
        <%_ } _%>
      <%_ } _%>
            )))
            .subscribe((<%= otherEntity.entityInstancePlural %>: I<%= otherEntity.entityAngularName %>[]) => (this.<%= otherEntity.entityInstancePlural %>SharedCollection.set(<%= otherEntity.entityInstancePlural %>)));
    <%_ } _%>
    <%_ for (const relationship of relationshipsWithCustomUniqueOptions) { %>
      <%_ const filter = relationship.otherEntity.jpaMetamodelFiltering ? `'${relationship.otherEntityRelationshipName}Id.specified': 'false'` : `filter: '${relationship.otherEntityRelationshipName.toLowerCase()}-is-null'`; _%>

        this.<%= relationship.otherEntityName %>Service
            .query({<%- filter %>})
            .pipe(map((res: HttpResponse<I<%= relationship.otherEntity.entityAngularName %>[]>) => res.body ?? []))
            .pipe(map((<%= otherEntity.entityInstancePlural %>: I<%= otherEntity.entityAngularName %>[]) => this.<%= otherEntity.entityInstance %>Service.add<%= otherEntity.entityAngularName %>ToCollectionIfMissing<I<%= otherEntity.entityAngularName %>>(<%= otherEntity.entityInstancePlural %>, this.<%= entityInstance %>?.<%= relationship.propertyName %>)))
            .subscribe((<%= otherEntity.entityInstancePlural %>: I<%= otherEntity.entityAngularName %>[]) => (this.<%= relationship.relationshipFieldNamePlural %>Collection.set(<%= otherEntity.entityInstancePlural %>)));
      <%_ } _%>
    <%_ } _%>
    }
<%_ } _%>
}
